package com.maikobi.maikobi.task;

import com.maikobi.maikobi.manager.AiManager;
import com.maikobi.maikobi.model.entity.Chart;
import com.maikobi.maikobi.model.enums.ChartStatus;
import com.maikobi.maikobi.service.ChartService;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Getter
public class ChartGenerateTask implements Runnable {

    private final Chart chart;
    private final Long biModelId;
    private final String userInput;
    private final ChartService chartService;
    private final AiManager aiManager;

    public ChartGenerateTask(Chart chart, Long biModelId, String userInput,
                             ChartService chartService, AiManager aiManager) {
        this.chart = chart;
        this.biModelId = biModelId;
        this.userInput = userInput;
        this.chartService = chartService;
        this.aiManager = aiManager;
    }

    @Override
    public void run() {
        try {
            // 1. 标记为“执行中”
            Chart updateChart = new Chart();
            updateChart.setId(chart.getId());
            updateChart.setStatus(ChartStatus.RUNNING); // running
            boolean updated = chartService.updateById(updateChart);
            if (!updated) {
                handleChartUpdateError(chart.getId(), "更新图表执行中状态失败");
                return;
            }

            // 2. 调用 AI 接口
            String result = aiManager.doChat(biModelId, userInput);
            String[] splits = result.split("【【【【【");
            if (splits.length < 3) {
                handleChartUpdateError(chart.getId(), "AI 生成结果格式错误");
                return;
            }

            // 3. 提取结果
            String genChart = splits[1].trim();
            String genResult = splits[2].trim();

            // 4. 保存成功结果
            Chart resultChart = new Chart();
            resultChart.setId(chart.getId());
            resultChart.setGenChart(genChart);
            resultChart.setGenResult(genResult);
            resultChart.setStatus(ChartStatus.SUCCEED); // succeed

            boolean saved = chartService.updateById(resultChart);
            if (!saved) {
                handleChartUpdateError(chart.getId(), "更新图表成功状态失败");
            }
        } catch (Exception e) {
            log.error("图表任务执行失败，chartId = {}", chart.getId(), e);
            handleChartUpdateError(chart.getId(), "图表任务执行异常：" + e.getMessage());
        }
    }

    private void handleChartUpdateError(Long chartId, String message) {
        Chart errorChart = new Chart();
        errorChart.setId(chartId);
        errorChart.setStatus(ChartStatus.FAILED); // failed
        errorChart.setExecMessage(message);
        boolean failUpdate = chartService.updateById(errorChart);
        if (!failUpdate) {
            log.error("图表任务失败状态更新失败，chartId = {}, message = {}", chartId, message);
        }
    }
}
